package top.huhuiyu.springboot2.study.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.huhuiyu.springboot2.study.base.BaseDataResult;
import top.huhuiyu.springboot2.study.base.BaseResult;
import top.huhuiyu.springboot2.study.base.PageBean;
import top.huhuiyu.springboot2.study.base.PageResult;
import top.huhuiyu.springboot2.study.entity.SoftwareType;
import top.huhuiyu.springboot2.study.mapper.SoftwareMapper;
import top.huhuiyu.springboot2.study.mapper.SoftwareTypeMapper;
import top.huhuiyu.springboot2.study.service.SoftwareTypeService;

import java.util.List;

/**
 * @author 胡辉煜
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SoftwareTypeServiceImpl implements SoftwareTypeService {
  private final SoftwareTypeMapper softwareTypeMapper;
  private final SoftwareMapper softwareMapper;

  @Override
  public BaseResult insert(SoftwareType softwareType) {
    // 查询名称是否存在
    SoftwareType check = softwareTypeMapper.queryByTname(softwareType);
    if (check != null) {
      return BaseResult.fail("名称已存在");
    }
    // 添加
    int result = softwareTypeMapper.insert(softwareType);
    return result == 1 ? BaseResult.ok("添加成功") : BaseResult.fail("添加失败");
  }

  @Override
  public BaseDataResult<SoftwareType> queryByKey(Integer stid) {
    SoftwareType softwareType = softwareTypeMapper.queryByKey(stid);
    if (softwareType == null) {
      return BaseDataResult.fail("查无数据", SoftwareType.class);
    }
    return BaseDataResult.ok(softwareType);
  }

  @Override
  public BaseResult update(SoftwareType softwareType) {
    // 查询名称是否存在
    SoftwareType check = softwareTypeMapper.queryByTname(softwareType);
    if (check != null && !check.getStid().equals(softwareType.getStid())) {
      return BaseResult.fail("名称已存在");
    }
    int result = softwareTypeMapper.update(softwareType);
    return result == 1 ? BaseResult.ok("修改成功") : BaseResult.fail("修改失败");
  }

  @Override
  public BaseDataResult<PageResult<List<SoftwareType>>> query(SoftwareType type, PageBean pageBean) {
    // pageBean= Optional.ofNullable(pageBean).orElse(new PageBean());

    PageHelper.startPage(pageBean.getPageNumber(), pageBean.getPageSize());
    Page<SoftwareType> page = (Page<SoftwareType>) softwareTypeMapper.query(type);
    // 思考一下怎么计算分页总数
    pageBean.setTotal(page.getTotal());
    return BaseDataResult.ok(PageResult.instance(pageBean, page.getResult()));
  }

  @Override
  public BaseResult delete(Integer stid) {
    Integer count = softwareMapper.queryCountByStid(stid);
    if (count > 0) {
      return BaseResult.fail("该类型下有软件，不能删除");
    }
    int result = softwareTypeMapper.delete(stid);
    return result == 1 ? BaseResult.ok("删除成功") : BaseResult.fail("删除失败");
  }

}
